import {permissionStatus} from "./constant";
const Notification = window.Notification || window.mozNotification || window.webkitNotification;

export default class Notice {
  constructor() {
    this.notice = null;
  }
}

/**
 * 当前是否授权
 * @returns Boolean
 */
Notice.isPermission= function() {
  return Notification.permission === permissionStatus.success;
}

/**
 * 当前是否已经拒绝授权
 * @returns Boolean
 */
 Notice.isRefuse= function() {
  return Notification.permission === permissionStatus.fail;
}

/**
 * 申请通知权限
 * @returns Promise
 */
 Notice.requestPermission = function() {
  return new Promise((resolve, reject) => {
    if (Notice.isPermission()) {
      return resolve(true);
    }
    Notification.requestPermission().then(function (permission) {
      // 用户同意权限
      if (permission === permissionStatus.success) {
        resolve(true);
      } else {
        resolve(false);
      }
    });
  })
}

/**
 * 调用浏览器api显示消息
 * @param {Object} options 
 */
Notice.noticeInit = function(options) {
  if (this.notice) {
    this.notice.close();
    this.notice = null;
  }
  this.notice = new Notification(options.title, {
    body: options.body,
    icon: options.icon,
    silent: options.silent || false
  });
  let data = options.data ? options.data : null;
  this.notice.onclick = function() {
    console.log("click");
    options.click && options.click(data);
  };
  this.notice.onerror = function(err) {
    options.error && options.error(err);
  };
  this.notice.onshow = function() {
    console.log("show");
    options.success && options.success(data);
  };
  this.notice.onclose = function() {
    console.log("close");
    options.close && options.close(data);
  };
}

/**
 * 显示通知消息,如果当前未授权提示用户授权，用户同意才会显示消息通知
 * @param {Obj} options
 * title: 通知标题
 * body: 通知的内容
 * icon: 消息通知的图标
 * click: 通知被点击的回调
 * success：通知显示成功回调
 * close: 通知关闭的回调
 */
 Notice.show = function(options) {
  let defaultOpt = {
    isForce: false
  };
  let params = Object.assign({},defaultOpt, options);
  if (Notice.isPermission()) {
    Notice.noticeInit(params);
  } else {
    // 如果是不强制弹消息的，用户拒绝授权后不再发起询问，MDN文挡是推荐此做法
    if (Notice.isRefuse()) {
      return;
    }
    Notice.requestPermission().then((permission) => {
      Notice.noticeInit(params);
    })
  }
}